package connector

import (
	"fmt"
	gameConfig "framework/game"
	"framework/net"
	"framework/remote"
	"go.uber.org/zap"
)

type Connector struct {
	isRunning    bool `json:"isRunning"`
	wsManager    *net.Manager
	ServerId     string
	handlers     net.LogicHandler //业务处理器
	remoteClient remote.Client
}

func Default() *Connector {
	return &Connector{
		handlers: make(net.LogicHandler),
	}
}

func (c *Connector) Run(serverId string) {
	if !c.isRunning {
		//启动Websocker
		c.wsManager = net.NewManager() //创建一个wsManager
		c.wsManager.ConnectorHandlers = c.handlers
		c.ServerId = serverId
		//启动nats客户端
		c.remoteClient = remote.NewNatsClient(serverId, c.wsManager.RemoteReadChan)
		c.remoteClient.Run()
		c.wsManager.RemoteCli = c.remoteClient
		c.Serve(serverId)
	}
}

func (c Connector) Close() {
	if c.isRunning {
		//进行关闭操作
		c.wsManager.Close()
		f := c.wsManager.Close
		f()
	}
}

/*
*
客户端进行连接时的入口方法
*/
func (c *Connector) Serve(serverId string) {
	zap.S().Infof("connector Serve get serverId:%s", serverId)
	//地址 需要读取配置文件 在游戏中可能加载很多的信息（配置） 如果写到yml可能会比较复杂 不容易维护
	//游戏中的配置 读取 一般采用json的方式 需要读取json的配置文件
	c.wsManager.ServerId = serverId
	connectorConfig := gameConfig.Conf.GetConnector(serverId)
	if connectorConfig == nil {
		zap.S().Errorf("no connectors game found")
	}
	addr := fmt.Sprintf("%s:%d", connectorConfig.Host, connectorConfig.ClientPort)
	c.isRunning = true
	c.wsManager.Run(addr)
}

/*
*
注册connector的处理器
*/
func (c *Connector) RegisterHandlers(handlers net.LogicHandler) {
	c.handlers = handlers
}
